package com.diandian.ms;



import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.diandian.common.Constant;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**
 * @description MobileFilter
 * @author TDW
 * @date 2016年12月28日
 *
 */
public class MobileServerFilter extends ZuulFilter {

    //private static final Logger log = Logger.getLogger(MobileServerFilter.class);
	private static final Logger logger = LogManager.getLogger(MobileServerFilter.class.getName());
    /** 灰度环境mobile server serverId */
    private static final String GRAY_MS_SERVER_ID = "gray_dd_mobile_server";
    /** mobile server正式环境serverId */
    private static final String MS_SERVER_ID = "dd_mobile_server";
    
    @Resource
    private JdbcTemplate jdbcTemplate;

    public boolean shouldFilter() {
        return true;
    }


    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest req = ctx.getRequest();
        String uri = req.getRequestURI();
        String appId = uri.split("/")[1];//
        if (appId.equalsIgnoreCase(Constant.mobileServer)) {
        	logger.info("#####request mobile server ："+uri);
        	String shopId = req.getParameter("shop_id");
        	final String orderId = req.getParameter("order_id");
        	if(uri.indexOf(Constant.URL_RESEND_ORDER) != -1){//PC端订单重打： 厨打、小票、标签、全部重打
        		shopId = getShopId(shopId, orderId);
        	}else if(uri.indexOf(Constant.URL_SEND_RE_PRENT) != -1){
        		shopId = getShopId(shopId, orderId);
        	}
        	logger.info("#####orderId ："+shopId+",shop_id="+shopId);
        	logger.info("###是否是灰度商家："+Constant.grayshops.contains(shopId));
    		if(Constant.grayshops.contains(shopId)){
    			ctx.set("serviceId", GRAY_MS_SERVER_ID);
    		}else{
    			ctx.set("serviceId", MS_SERVER_ID);
    		}
        }
        return null;
    }


	private String getShopId(String shopId, final String orderId) {
		if(StringUtils.isBlank(shopId)){
			try{
				shopId = jdbcTemplate.queryForObject("select shop_id from orderlist where id=?",new Object[]{orderId}, new RowMapper<String>() {
					public String mapRow(ResultSet rs, int arg1) throws SQLException {
						if(rs == null)
							throw new RuntimeException("无此订单数据，order_id: "+orderId);
						Long s = rs.getLong("shop_id");
						return s+"";
					}
				});
			}catch(Exception e){
				logger.error(e);
				throw new RuntimeException("无此订单数据，order_id: "+orderId);//统一交给异常拦截器处理
			}
		}
		return shopId;
	}


    public String filterType() {
        return "pre";
    }


    public int filterOrder() {
        return 1;
    }

}

